package com.zzw.springboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzw.springboot.bean.ProductCategory;
import com.zzw.springboot.bean.Supplier;
import com.zzw.springboot.mapper.ProductCategoryMapper;
import com.zzw.springboot.mapper.SupplierMapper;
import com.zzw.springboot.service.ProductCategoryService;
import com.zzw.springboot.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品分类服务实现类
 */
@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements ProductCategoryService {

    @Autowired
    private ProductCategoryMapper categoryMapper;

    @Override
    @Transactional
    public boolean addCategory(ProductCategory category) {
        // 检查分类名称是否已存在
        if (checkCategoryNameExists(category.getCategoryName(), category.getParentId(), null)) {
            return false;
        }
        return categoryMapper.insertCategory(category) > 0;
    }

    @Override
    @Transactional
    public boolean updateCategory(ProductCategory category) {
        // 检查分类名称是否已存在（排除自身）
        if (checkCategoryNameExists(category.getCategoryName(), category.getParentId(), category.getCategoryId())) {
            return false;
        }
        return categoryMapper.updateCategory(category) > 0;
    }

    @Override
    @Transactional
    public boolean deleteCategory(Integer categoryId) {
        // 检查是否有子分类
        if (hasChildren(categoryId)) {
            return false;
        }
        return categoryMapper.deleteCategory(categoryId) > 0;
    }

    @Override
    public ProductCategory getCategoryById(Integer categoryId) {
        return categoryMapper.selectCategoryById(categoryId);
    }

    @Override
    public List<ProductCategory> getCategoryList(ProductCategory category) {
        return categoryMapper.selectCategoryList(category);
    }

    @Override
    public List<ProductCategory> getAllCategories() {
        return categoryMapper.selectAllCategories();
    }

    @Override
    public boolean hasChildren(Integer categoryId) {
        return categoryMapper.selectChildCount(categoryId) > 0;
    }

    @Override
    public boolean checkCategoryNameExists(String categoryName, Integer parentId, Integer categoryId) {
        return categoryMapper.checkCategoryNameExists(categoryName, parentId, categoryId) > 0;
    }
}
